import React, {Component, lazy, Suspense} from 'react';
import {connect} from 'react-redux';
import Proptypes from 'prop-types';
import {HashRouter, Route, Switch, Redirect} from 'react-router-dom';
import {authAsync} from './redux/actions';

import Loading from '@/components/Loading/Loading';
import {Toast} from "antd-mobile";

const Main = lazy(() => import('@/containers/main/Main'));
const Register = lazy(() => import('@/containers/register/Register'));
const Login = lazy(() => import('@/containers/login/Login'));
const Nothing = lazy(() => import('@/containers/nothing/Nothing'));
const Pushjob = lazy(() => import('@/components/Pushjob'));
const Test = lazy(() => import('@/containers/Test'));


class App extends Component {

    static propTypes = {
        user: Proptypes.object.isRequired,
        doConnect: Proptypes.func.isRequired
    }

    //生命周期
    componentDidMount() {
        //重新获取状态
        let {doConnect, user: {user}} = this.props;

        if(localStorage.getItem('token')){
            doConnect(user, (code, msg) => {
                if (code !== 0) {
                    localStorage.removeItem('token')
                    Toast.fail(msg, 1);
                }

            })
        }

    }

    render() {
        let token = localStorage.getItem('token');
        return (
            <HashRouter>
                <Suspense fallback={<Loading/>}>
                    <Switch>
                        <Redirect exact from="/" to={token?'/home':'/login'}/>
                        <Route path="/home" component={Main}/>
                        <Route path="/pushjob" component={Pushjob}/>
                        <Route path="/register" component={Register}/>
                        <Route path="/login" component={Login}/>
                        <Route path="/test">
                            <Test name="自定义props">
                                <p ref='a'>- <b>props.children</b>是<i> react </i>插槽？</p>
                                <p ref='b'>- ？？？</p>
                            </Test>

                        </Route>
                        <Route component={Nothing}/>
                    </Switch>
                </Suspense>
            </HashRouter>
        );
    }

}

function mapStateToProps(state) {
    return {
        user: state.user
    }
}

function mapDispatchToProps(dispatch) {
    return {
        doConnect: (user, callback) => dispatch(authAsync(user, callback))
    }
}

export default connect(
    mapStateToProps,
    mapDispatchToProps
)(App)
